package cn.uniquesoft.util;

import java.io.*;
import java.net.*;

public class HttpUtil {

	// private static final Log logger = Logs.get();
	private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
	private final static String DEFAULT_ENCODING = "UTF-8";

	public static String postData(String urlStr, String data) {
		return postData(urlStr, data, null);
	}

	public static String postData(String urlStr, String data, String contentType) {
		BufferedReader reader = null;
		try {
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			conn.setReadTimeout(CONNECT_TIMEOUT);
			if (contentType != null) {
				conn.setRequestProperty("content-type", contentType);
			}
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
			if (data == null) {
				data = "";
			}
			writer.write(data);
			writer.flush();
			writer.close();

			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
				sb.append("\r\n");
			}
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
			// logger.error("Error connecting to " + urlStr + ": " +
			// e.getMessage());
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
			}
		}
		return null;
	}
	
//	public static void main(String[] args){
//		String url = "http://www.unique-soft.cn:8088/bst/topupdetails/weixin_notify";
//		String data = "<xml><appid><![CDATA[wxecaef476b344251f]]></appid><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[N]]></is_subscribe><mch_id><![CDATA[1378896402]]></mch_id><nonce_str><![CDATA[6110f00e7572422c9cf09f55e6322c26]]></nonce_str><openid><![CDATA[ocapiwShKHC-uUVh0G0gNigbJ9yk]]></openid><out_trade_no><![CDATA[37064dc72c62439da1c7078cc68c1087]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[70583F35D9643828908EDCE13022C5C7]]></sign><time_end><![CDATA[20180111150120]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[NATIVE]]></trade_type><transaction_id><![CDATA[4200000090201801112171630794]]></transaction_id></xml>";
//		String param = "<xml><></xml>";
//		sendPost(url,data);
//	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

    /**
     * 采用get方式请求url.获取返回的信息并返回
     * @param url
     * @return
     */
	public static String doHttpsGetJson(String url){
		String message="";
		try {
//			System.out.println("doHttpsGetJson");
			URL urlGet = new URL(url);
			HttpURLConnection http =(HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET");
			http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒28
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒29 30
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			message = new String(jsonBytes,"UTF-8");
		}catch (MalformedURLException e){
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}
		return message;
	}

    /**
     * 采用post的方式进行
     * @param
     * @param menu
     * @return
     */
	public static String doHttpsPostJson(String uri, String menu){

        try {
            URL url = new URL(uri);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            httpURLConnection.connect();
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒28
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒29 30
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(menu.getBytes("UTF-8"));
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
            StringBuffer sb = new StringBuffer();
            String str = "";
            while ((str = reader.readLine()) != null)
            {
                sb.append(str).append("\n");
            }
            String text = inputStream.toString();

//            System.out.println(text);
            return sb.toString();

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

    public  static void main(String[] args){
//        String url = "https://api.weixin.qq.com/cgi-bin/token?appid=wx97a224ecbb97cd1a&secret=964e7825d56b5a6dc8a7dd00c5132dd4&grant_type=client_credential";
//        String txt = doHttpsGetJson(url);
//        System.out.println(txt);
//        String ss = "9_HrwDntZy7GHhsJVp0Y8VYqT4prcc--cC9GytmLaf0Ur564ZUm8C51W19PW8yKNO5j6AIAPG5xvlwZXles5evD-bMbDBEl2hm-jEpPQPjo_6zvq7VUm-yTuBD0WqMsW1VyrF6Xg9FpRSKejhKGJVeAIAORD";
//        String uri = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN",ss);
//        String menu = "{" +
//                "    \"button\": [" +
//                "        {" +
//                "            \"type\": \"view\", " +
//                "            \"name\": \"开始考试\", " +
//                "            \"url\": \"http://www.unique-info.cn/bst/wechat/redirect_userinfo\"" +
//                "        }" +
//                "    ]" +
//                "}";
//        //通过Appid ，appsecret生成获取access_token，然后动态获取
//        String jsonStr = HttpUtil.doHttpsPostJson(uri,menu);
//        System.out.println(jsonStr);

//		String param = "{\"username\":\"" + "ceshi1234" + "\",\"password\":\"" + "ceshi1234" + "\",\"nickname\":\"" + "ceshi1234"+"\"}";
//		String msg = HttpUtil.doHttpsPostJson("https://a1.easemob.com/1109190102042188/jrgwapp/users", param);
//		System.out.println(msg);

//		doDelete("https://a1.easemob.com/1109190102042188/jrgwapp/users/user1");
	}

	/**
	 * 删除
	 * @param urlToRead
	 * @return
	 */
	public static String doDelete(String urlToRead) {
		String message="";
		try {
			URL url = new URL(urlToRead);
			HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
			httpCon.setDoOutput(true);
			httpCon.setRequestProperty(
                    "Content-Type", "application/x-www-form-urlencoded" );
			httpCon.setRequestProperty(
					"Authorization", "Bearer YWMt91KAYBiVEemGaHNfKadYOwAAAAAAAAAAAAAAAAAAAAG78nygDlkR6Y5WXyNYeO8yAgMAAAFoUGGVIABPGgAEs1tyjpLNRLzIQ34dME2g_DCxa1Uo3uYsB78aQIn4Lg" );
			httpCon.setRequestMethod("DELETE");
			httpCon.connect();
			httpCon.disconnect();
			InputStream is = httpCon.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			message = new String(jsonBytes,"UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return message;
	}

}

